// Copyright (c) Appeon. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. 
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.

using System.Text;
using System;

namespace SnapObjects.Data
{
    internal class TNodeWriter : INodeWriter
    {
        private readonly StringBuilder _builder;

        public TNodeWriter()
        {
            _builder = new StringBuilder();
        }

        public INodeWriter WriteAsArray(string name)
        {
            return this;
        }

        public INodeWriter WriteAsObject(string name)
        {
            return this;
        }

        public INodeWriter WriteAsValue(string name)
        {
            if (_builder.Length > 0 && _builder[_builder.Length - 1] != '\n')
            {
                _builder.Append("\t");
            }

            return this;
        }

        public void WriteEndArray()
        {
            if (_builder.Length > 0 && _builder[_builder.Length - 1] != '\n')
            {
                _builder.AppendLine();
            }
        }

        public void WriteEndObject()
        {
            _builder.AppendLine();
        }

        public void WriteNull()
        {
            _builder.Append("null");
        }

        public void WriteRawValue(string raw)
        {
            _builder.Append(raw);
        }

        public void WriteValue(object value)
        {
            _builder.Append(this.AddQuotation(value) ?? "null");
        }

        public override string ToString()
        {
            return _builder.ToString();
        }

        private object AddQuotation(object value)
        {
            if (value is DateTime dt)
            {
                return dt.ToString("yyyy-MM-dd HH:mm:ss.fffffff");
            }

            return value != null && !value.GetType().IsValueType
                ? $"\"{value}\"" : value;
        }
    }
}
